package org.jeecg.config.app;

import com.alibaba.fastjson.JSONObject;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.TransferModel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.HttpUtil;
import org.jeecg.config.vo.WxPayVo;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 微信工具
 * @author: Young Jun
 * @date: 2023年06月17日 16:21
 */
@Slf4j
public class WechatUtil {
    private static String miniAppID;
    private static String miniSecret;
    private static String mchId;
    private static String grantType;
    private static WxPayProperties wxPayProperties;

    public static void setMiniAppID(String miniAppID) {
        WechatUtil.miniAppID = miniAppID;
    }

    public static void setMiniSecret(String miniSecret) {
        WechatUtil.miniSecret = miniSecret;
    }

    public static String getMiniAppID() {
        return miniAppID;
    }

    public static String getMiniSecret() {
        return miniSecret;
    }

    public static void setWxPayProperties(WxPayProperties wxpay) {
        wxPayProperties = wxpay;
    }

    public static WxPayProperties getWxPayProperties() {
        return wxPayProperties;
    }

    public static String requestGetAppId(String code) {
        String result = "";
        String url = "";
        try {
            //请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现
            url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                    + getMiniAppID() + "&secret="
                    + getMiniSecret() + "&js_code="
                    + code
                    + "&grant_type=authorization_code";
            log.info("微信请求地址：{}", url);
            result = HttpUtil.doGet(url, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static JSONObject requestGetAccessToken() {
        String result = "";
        try {
            result = HttpUtil.doGet(
                    "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                            "&appid=" + miniAppID +
                            "&secret=" + miniSecret, null);
        } catch (Exception e) {
            log.error("微信requestGetAccessToken:{}" ,e);
            e.printStackTrace();
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject getPhoneNumber(String accessToken, String code) {
        String result = "";
        try {
            Map<String, Object> body = new HashMap<>();
            body.put("code", code);
            result = HttpUtil.doPostJson(
                    "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, body);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("微信getPhoneNumber:{}" ,e);
        }
        return JSONObject.parseObject(result);
    }

    public static boolean wxPay(WxPayVo vo) {
        Map<String, String> params = TransferModel.builder()
                .mch_appid(wxPayProperties.getAppId())
                .mchid(wxPayProperties.getMchId())
                .nonce_str(WxPayKit.generateStr())
                .partner_trade_no(vo.getTrade_no())
                .openid(vo.getOpenid())
                .check_name("NO_CHECK")
                .amount(String.valueOf(vo.getMoney().multiply(new BigDecimal("100")).longValue()))
                .desc(vo.getDesc())
                .spbill_create_ip(vo.getIp())
                .build()
                .createSign(wxPayProperties.getMchKey(), SignType.MD5, false);
        log.info("微信提现params:" + JSONObject.toJSONString(params));
        // 提现
        String transfers = WxPayApi.transfers(params, wxPayProperties.getCertPath(), wxPayProperties.getMchId());
        log.info("微信提现结果:" + transfers);
        Map<String, String> map = WxPayKit.xmlToMap(transfers);
        String returnCode = map.get("return_code");
        String resultCode = map.get("result_code");
        if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(resultCode)) {
            // 提现成功
            return true;
        } else {
            // 提现失败
            return false;
        }
    }
}
